import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
    private final byte[] md5;

    public MD5(Path file) throws NoSuchAlgorithmException, IOException {
        System.out.printf("  checking MD5 for \"%s\"",file.getFileName()).println();
        MessageDigest md = MessageDigest.getInstance("MD5");
        InputStream is = Files.newInputStream(file);
        byte buffer[]=new byte[16384];
        int length;
        while ((length=is.read(buffer))!=-1) {
            md.update(buffer,0,length);
        }
         md5=md.digest();
    }

    public MD5(String hex) {
        md5=DatatypeConverter.parseHexBinary(hex);
    }

    public String toString() {
        return DatatypeConverter.printHexBinary(md5);
    }

    public boolean equals(MD5 other) {
        return MessageDigest.isEqual(md5, other.md5);
    }
}
